package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.feign.ArticleFeign;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.MediaEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmMaterialService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-29
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    private IWmMaterialService wmMaterialService;
    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private IAuditService auditService;
    @Override
    public ResponseResult listByPage(WmNewsPageDto dto) {
        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if(ObjectUtils.isNotEmpty(dto.getStatus())){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if (ObjectUtils.isNotEmpty(dto.getChannelId())) {
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        if (ObjectUtils.isNotEmpty(dto.getBeginPubDate()) && ObjectUtils.isNotEmpty(dto.getEndPubDate())) {
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        this.page(page,queryWrapper);
        return new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal(),page.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //每个人的文章和素材都不一样，在保存的时候需要从threadlocal中获取userid
        User user = UserThreadLocalUtil.get();
        if(ObjectUtils.isEmpty(user)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        wmNews.setUserId(user.getUserId());
        if(ObjectUtils.isEmpty(wmNews.getPublishTime())){
            wmNews.setPublishTime(new Date());
        }
        wmNews.setSubmitedTime(new Date());
        //前端传过来的封面图片是数组，数据库需要的数据是图片的url,url的格式，需要进行一个转换
        String images =  transferImages(wmNewsDto,wmNews);
        wmNews.setImages(images);
        if(ObjectUtils.isNotEmpty(wmNews.getId())){
            //如果前台传过来的数据有id，则是更新，需要更新本表，并删除之前的关联信息，重新保存关联信息
            wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_COMMIT.getVal());
            this.updateById(wmNews);
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WmNewsMaterial::getNewsId,wmNews.getId());
            wmNewsMaterialService.remove(queryWrapper);
            saveMaterial(wmNewsDto,wmNews.getId());
        }else {
            //除了保存文章表，还需要保存素材文章关联表
            this.save(wmNews);
            saveMaterial(wmNewsDto,wmNews.getId());
        }
        //TODO 文本审核
        auditService.audit(wmNews);
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 保存至关联表
     * @param wmNewsDto
     * @param wmNewsId
     */
    private void saveMaterial(WmNewsDto wmNewsDto,Integer wmNewsId) {
        //保存封面部分至关联表
        List<ImageDto> images = wmNewsDto.getImages();
        if (ObjectUtils.isNotEmpty(images)) {
            int i=0;
            for (ImageDto image : images) {
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setMaterialId(image.getId());
                wmNewsMaterial.setNewsId(wmNewsId);
                wmNewsMaterial.setType(1);
                wmNewsMaterial.setOrd(i++);
                wmNewsMaterialService.save(wmNewsMaterial);
            }
        }
        List<ImageDto> imagesFromContent = getImagesFromContent(wmNewsDto);
        int j =0;
        for (ImageDto imageDto : imagesFromContent) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(imageDto.getId());
            wmNewsMaterial.setNewsId(wmNewsId);
            wmNewsMaterial.setType(0);
            wmNewsMaterial.setOrd(j++);
            wmNewsMaterialService.save(wmNewsMaterial);
        }
    }

    /**
     * 将封面的image转换成数据库中image需要的格式
     * @param wmNewsDto
     * @param wmNews
     * @return
     */
    private String transferImages(WmNewsDto wmNewsDto,WmNews wmNews) {
        Integer type = wmNewsDto.getType();
        //无图
        if(type==0){
            return null;
        }
        //单图
        if(type==1){
            ImageDto imageDto = wmNewsDto.getImages().get(0);
            return imageDto.getUrl();
        }
        //三图
        if(type==3){
            List<ImageDto> images = wmNewsDto.getImages();
            String imagesString = "";
            for (int i = 0; i < images.size(); i++) {
                String str = images.get(i).getUrl() ;
                if(i!=images.size()-1){
                    str+=",";
                }
                imagesString = imagesString + str;
            }
            return imagesString;
        }
        //自动
        if(type==-1){
            List<ImageDto> imageDtos =  getImagesFromContent(wmNewsDto);
            int size = imageDtos.size();
            if(size>=3){
                String imagesString = "";
                for (int i = 0; i < imageDtos.size(); i++) {
                    String str = imageDtos.get(i).getUrl() ;
                    if(i!=imageDtos.size()-1){
                        str+=",";
                    }
                    imagesString = imagesString + str;
                }
                wmNews.setType(3);
                return imagesString;
            }else if(size==0){
                wmNews.setType(0);
                return null;
            }else {
                wmNews.setType(1);
                return imageDtos.get(0).getUrl();
            }
        }
        return null;
    }

    /**
     * 从内容中获取图片
     * @param wmNewsDto
     * @return
     */
    private List<ImageDto> getImagesFromContent(WmNewsDto wmNewsDto) {
        String content = wmNewsDto.getContent();
        List<ContentDto> contentDtos = JSON.parseArray(content,ContentDto.class);
        List<ImageDto> imageDtos = new ArrayList<>();
        for (ContentDto contentDto : contentDtos) {
            if ("image".equals(contentDto.getType())) {
                ImageDto imageDto = new ImageDto();
                imageDto.setUrl(contentDto.getValue());
                imageDto.setId(contentDto.getId());
                imageDtos.add(imageDto);
            }
        }
        return imageDtos;
    }

}
